<template>
	<div>
		<Tabs style="overflow: initial;">
			<TabPane label="新增自提点">
				<Form label-position="top" ref="form" :model="formData" :rules="formRules" @submit.native.prevent>
					<FormDescItem label="自提点名称" prop="name" desc="设置自提点名称，自提点名称会显示在前台">
						<Input v-model="formData.name"></Input>
					</FormDescItem>
					<FormDescItem label="所在地区" prop="area" desc="设置自提点所在地区，会显示在前台选择自提点位置">
						<Cascader v-model="formData.area" :data="areas"></Cascader>
					</FormDescItem>
					<FormDescItem label="详细地址" prop="detail" desc="设置自提点详细地址，会显示在前台选择自提点位置">
						<Input v-model="formData.detail"></Input>
					</FormDescItem>
					<FormDescItem label="联系人" prop="realname" desc="设置自提点联系人姓名">
						<Input v-model="formData.realname"></Input>
					</FormDescItem>
					<FormDescItem label="联系电话" prop="mobile" desc="设置自提点联系电话，会显示在前台选择自提点位置(座机区号请用-隔开，如：400-0000000)">
						<Input v-model="formData.mobile"></Input>
					</FormDescItem>
					<FormDescItem label="营业时间" prop="saletime" desc="设置自提点营业时间，会显示在前台自提点详情介绍">
						<TimePicker v-model="formData.saletime" confirm type="timerange" placement="bottom-start"></TimePicker>
					</FormDescItem>
					<FormDescItem label="自提点图片" desc="自提点图片最多上传5张图片，上传后可点击查看大图，建议尺寸为：800px × 800px">
						<div style="font-size: 0;">
							<ImageCells :value="formData.imgs" :width="50" preview remove></ImageCells>
							<SelectImage v-if="formData.imgs.length < 5" @click="showMaterialLibrary = true" />
						</div>
					</FormDescItem>
					<FormDescItem label="自提点介绍" prop="desc" desc="设置自提点详细介绍，详细介绍会在自提点详情中展示">
						<Input v-model="formData.desc" type="textarea" :rows="4"></Input>
					</FormDescItem>
					<FormDescItem label="交通提示" prop="bus" desc="设置自提点周边交通及到自提点的交通出行指导">
						<Input v-model="formData.bus" type="textarea" :rows="4"></Input>
					</FormDescItem>
					<FormDescItem label="自提点类型" desc="请选择自提点类型">
						<RadioGroup v-model="formData.type">
			                <Radio :label="1">自提</Radio>
			                <Radio :label="2">核销</Radio>
			                <Radio :label="3">同时支持</Radio>
			                <Radio :label="0">不支持</Radio>
			            </RadioGroup>
					</FormDescItem>
					<FormDescItem label="是否启用" desc="选择是否使用自提点">
						<RadioGroup v-model="formData.status">
			                <Radio :label="1">启用</Radio>
			                <Radio :label="0">禁用</Radio>
			            </RadioGroup>
					</FormDescItem>
				</Form>
				<div class="map-wrap">
					<div class="map-cont">
						<h4 class="title">地图定位</h4>
						<div class="search-map" style="width: 480px;">
							<Input v-model="locationStr" search enter-button placeholder="输入地址查询" @on-search="handleGetTheLocation" />
						</div>
						<div class="map-group">
							<div id="allmap" class="allmap" style="height: 560px;"></div>
						</div>
					</div>
				</div>
				<div style="margin-top: 20px;">
					<Button type="default" @click="handleBack">返回列表</Button>
					<Button type="primary" :loading="committing" @click="handleSubmit">保存设置</Button>
				</div>
			</TabPane>
		</Tabs>
		
		<MaterialLibrary v-model="showMaterialLibrary" :max="5" @change="handleSelectImage"></MaterialLibrary>
		
		<LoadingMask v-if="loading"></LoadingMask>
		
	</div>
</template>

<script>
import BMap from 'BMap';
import Util from '@/libs/util.js';
import FormDescItem from '@/components/form/FormDescItem.vue';
import SelectImage from '@/components/SelectImage.vue';
import ImageCells from '@/components/ImageCell/cells.vue';
import MaterialLibrary from '@/components/MaterialLibrary.vue';
import LoadingMask from '@/components/LoadingMask.vue';
export default {
	name: "appPickSiteEdit",
	components: {
		FormDescItem,
		SelectImage,
		ImageCells,
		MaterialLibrary,
		LoadingMask
	},
	data() {
		var validPhone = (rule, value, callback) => {
			var isPhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/; //手机号码
			var isMob = /^0?1[3|4|5|8][0-9]\d{8}$/; // 座机格式
			if(isMob.test(value) || isPhone.test(value)) {
				callback();
			} else {
				callback('请输入正确的联系方式');
			}
		};
		return {
			loading: false,
			committing: false,
			showMaterialLibrary: false,
			mapExam: undefined, // 地图实例
			locationStr: '', // 地址信息
			formData: {
				id: '',
				name: '',
				district_id: '',
				area: [],
				detail: '',
				lat: '',
				lng: '',
				status: 1,		// 状态 1 启用 0 禁用
				type: 1,		// 类型 0 不支持 1 自提 2 核销 3 同时支持
				realname: '',
				mobile: '',
				imgs: [],
				desc: '',
				bus: '',
				saletime: [],
				bus: ''
			},
			formRules: {
				name: [
					{ required: true, message: "请输入自提点名称", trigger: "blur" }
				],
				area: [
					{ required: true, type: 'array', message: "请选择所在地区", trigger: "change" }
				],
				detail: [
					{ required: true, message: "请输入详细地址", trigger: "blur" }
				],
				realname: [
					{ required: true, message: "请输入联系人姓名", trigger: "blur" }
				],
				mobile: [
					{ required: true, message: "请输入联系电话", trigger: "blur" },
					{ validator: validPhone, trigger: 'blur' }
				],
				saletime: [
					{ required: true, type: 'array', message: "请选择营业时间", trigger: "change" }
				],
				desc: [
					{ required: true, message: "请输入自提点描述", trigger: "blur" }
				],
				bus: [
					{ required: true, message: "请输入交通提示", trigger: "blur" }
				]
			}
		};
	},
	computed: {
        areas () {
            return this.$store.state.app.areas;
        }
    },
	mounted() {
		
		// 实例化地图
		this.mapExam = new BMap.Map("allmap"); // 创建地图实例  
		this.mapExam.centerAndZoom(new BMap.Point(116.331398, 39.897445), 11); // 初始化地图，设置中心点坐标和地图级别      
		this.mapExam.setCurrentCity("北京");
		this.mapExam.enableScrollWheelZoom(); //启用滚轮放大缩小，默认禁用
		this.mapExam.enableContinuousZoom(); //启用地图惯性拖拽，默认禁用

		// 地图点击事件
		this.mapExam.addEventListener("click", (e) => {
			/*// 清除已有覆盖物
	  		this.mapExam.clearOverlays();
	  		// 添加覆盖物
			this.mapExam.addOverlay(new BMap.Marker(e.point));
	  		// 设置中心点
	  		this.mapExam.panTo(e.point);*/
			// this.mapExam.setCenter(e.point);
			// this.mapExam.centerAndZoom(e.point, 16);
		});

		// 编辑
		if(this.$route.query.id) {
			// 获取对应的自提点数据
			this.loadData();
		} else {
			// 初始定位
			this.handleInitLocation();
		}
	},
	methods: {
		loadData() {
			this.loading = true;
			Util.ajax.post(this.API['API_APP_STORE_DETAIL'], {id: this.$route.query.id}).then(res => {
				this.loading = false;
				this.formData.id = this.$route.query.id;
				this.formData.name = res.name;
				this.formData.area = res.area.split(',').map(item => {
					return Number(item);
				});
				this.formData.detail = res.detail;
				this.formData.realname = res.realname;
				this.formData.mobile = res.mobile;
				this.formData.saletime = [res.open_time, res.end_time];
				this.formData.imgs = res.imgs ? res.imgs.split(',') : [];
				this.formData.desc = res.desc;
				this.formData.bus = res.bus;
				this.formData.status = res.status;
				this.formData.type = res.type;
				this.handleSetCoordsLocation(res.lng, res.lat, res.detail);
			}).catch(() => {
				
			})
		},
		// 初始定位
		handleInitLocation() {
			let map = this.mapExam;
			// 浏览器定位
			let geolocation = new BMap.Geolocation();
			geolocation.getCurrentPosition(function(r) {
				if(this.getStatus() == BMAP_STATUS_SUCCESS) {
					if(r.point.lng == 0 && r.point.lat == 0) {
						theIPLocation();
					} else {
						// map.addOverlay(new BMap.Marker(r.point));
						// map.panTo(r.point);
						map.centerAndZoom(r.point, 16);
					}
				} else {
					theIPLocation();
				}
			}, {
				enableHighAccuracy: true
			});

			// IP定位，浏览器定位失败时调用此方法
			function theIPLocation() {
				let myCity = new BMap.LocalCity();
				myCity.get(function(result) {
					map.addOverlay(new BMap.Marker(result.center));
					map.setCenter(result.name);
					map.setCurrentCity(result.name);
				})
			}
		},
		// 根据地址信息定位
		handleGetTheLocation() {
			if(this.locationStr) {
				this.mapExam.clearOverlays();
				this.mapExam.centerAndZoom(this.locationStr, 18);
				var local = new BMap.LocalSearch(this.mapExam, {
					renderOptions: {
						map: this.mapExam
					}
				});
				local.search(this.locationStr);
			}
		},
		// 根据坐标定位
		handleSetCoordsLocation(lng, lat, title) {
			let point = new BMap.Point(lng, lat);
			this.mapExam.clearOverlays();
			this.mapExam.addOverlay(new BMap.Marker(point));
			this.mapExam.centerAndZoom(point, 16); // 初始化地图，设置中心点坐标和地图级别
			this.mapExam.openInfoWindow(new BMap.InfoWindow(title, {
				width: 250,
				height: 18,
				offset: {
					width: 0,
					height: -30
				}
			}), point); //开启信息窗口
		},
		// 选择的图片
		handleSelectImage(images) {
			this.formData.imgs = images.map(item => {
				return item.url;
			});
		},
		handleBack() {
			this.$router.back();
		},
		handleSubmit() {
			if(this.committing) return false;
			this.$refs.form.validate((valid) => {
				if(valid) {
					let point = this.mapExam.getCenter();
					if(!point || (point.lng == 0 && point.lat == 0)) {
						this.$Message.error('请标记自提点所在坐标');
						return false;
					}
					let form = this.formData;
					let method = this.API['API_APP_STORE_CREATE'];
					let params = {
						name: form.name,
						district_id: form.area[form.area.length - 1],
						area: form.area.join(','),
						detail: form.detail,
						lat: point.lat,
						lng: point.lng,
						status: form.status,
						type: form.type,
						realname: form.realname,
						mobile: form.mobile,
						imgs: form.imgs.join(','),
						desc: form.desc,
						bus: form.bus,
						open_time: form.saletime[0],
						end_time: form.saletime[1],
						bus: form.bus
					}
					
					if(form.id) {
						method = this.API['API_APP_STORE_SAVE'];
						params.id = form.id;
					}
					
					this.committing = true;
					Util.ajax.post(method, params).then((res) => {
						this.$Message.success({
							content: "保存成功",
							onClose: () => {
								this.handleBack();
							}
						});
					}).catch(() => {
						this.committing = false;
					})
				}
			})
		}
	}
};
</script>
<style scoped>
.map-wrap {
	border-top: 1px solid #e1e1e1;
}

.map-wrap .map-cont {
	width: 1120px;
}

.map-wrap .title {
	margin: 10px 0;
	font-size: 14px;
	color: #000;
	font-weight: 400;
}

.search-map {
	width: 100%;
	height: 32px;
	margin-bottom: 20px;
}

.search-map .ivu-input-wrapper {
	width: 100%;
	float: left;
}

.search-map .ivu-input {
	border-right: 0;
	border-top-right-radius: 0;
	border-bottom-right-radius: 0;
}

.search-map>.ivu-btn {
	padding: 0;
	float: left;
	width: 50px;
	border-top-left-radius: 0;
	border-bottom-left-radius: 0;
	height: 32px;
	line-height: 32px;
	font-size: 14px;
}

.map-group {
	width: 100%;
	height: 560px;
	overflow: hidden;
}
</style>